<!-- src/views/njtuser/member/user/index.vue -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧导航栏 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>导航栏</span>
            </div>
            <div class="text item">
              <el-menu
                :default-active="activeMenu"
                class="el-menu-vertical-demo"
                @select="handleMenuSelect">
                <el-menu-item index="all">
                  <i class="el-icon-user"></i>
                  <span slot="title">所有用户</span>
                </el-menu-item>
                <el-menu-item index="incomplete">
                  <i class="el-icon-warning-outline"></i>
                  <span slot="title">未完善信息用户</span>
                </el-menu-item>
                <el-submenu index="organizations">
                  <template slot="title">
                    <i class="el-icon-office-building"></i>
                    <span>所属单位</span>
                  </template>
                  <el-menu-item
                    v-for="org in organizations"
                    :key="org.id"
                    :index="'org_' + org.id">
                    <span>{{ org.unitName }}</span>
                  </el-menu-item>
                </el-submenu>
              </el-menu>
            </div>
          </el-card>
        </div>
      </el-col>

      <!-- 右侧用户列表 -->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="主体名称" prop="companyName">
            <el-input
              v-model="queryParams.companyName"
              placeholder="请输入主体名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobilePhone">
            <el-input
              v-model="queryParams.mobilePhone"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['nongjt:user:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['nongjt:user:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['nongjt:user:remove']"
            >删除</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" />
          <el-table-column label="主体名称" align="center" prop="companyName" />
          <el-table-column label="电话号码" align="center" prop="mobilePhone" />
          <el-table-column label="注册时间" align="center" prop="registerTime" width="180">
            <template slot-scope="scope">
              <span>{{ formatDate(scope.row.registerTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="信息是否完善" align="center" prop="perfectFlag">
            <template slot-scope="scope">
              <el-tag :type="scope.row.perfectFlag === '1' ? 'success' : 'danger'">
                {{ scope.row.perfectFlag === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否会员" align="center" prop="memberFlag">
            <template slot-scope="scope">
              <el-tag :type="scope.row.memberFlag === '1' ? 'success' : 'danger'">
                {{ scope.row.memberFlag === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所属单位" align="center" prop="organizationName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['nongjt:user:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['nongjt:user:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入主体名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobilePhone">
              <el-input v-model="form.mobilePhone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" type="password" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="省市区" prop="province">
              <el-cascader
                v-model="selectedArea"
                :options="areaOptions"
                :props="areaProps"
                placeholder="请选择省市区"
                clearable
                style="width: 100%"
                @change="handleAreaChange">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否会员" prop="memberFlag">
              <el-select v-model="form.memberFlag" placeholder="请选择是否会员">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态" prop="userStatus">
              <el-select v-model="form.userStatus" placeholder="请选择用户状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="冻结" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信息完善" prop="perfectFlag">
              <el-select v-model="form.perfectFlag" placeholder="请选择信息是否完善">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册时间" prop="registerTime">
              <el-date-picker
                v-model="form.registerTime"
                type="datetime"
                placeholder="请选择注册时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsers, listOrganizations, listIncompleteUsers, getUser, addUser, updateUser, delUser } from "@/api/nongjt/user";
import { getAllProvinces, getCitiesByProvinceId, getDistrictsByCityId } from "@/api/nongjt/area";

export default {
  name: "NjtUser",
  dicts: ['njt_perfect_flag', 'njt_member_flag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 单位列表
      organizations: [],
      // 当前激活菜单
      activeMenu: "all",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 省市区级联配置
      areaProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        lazy: true,
        lazyLoad: this.loadAreaData
      },
      // 省市区选项
      areaOptions: [],
      // 选中的省市区 [省ID, 市ID, 区ID]
      selectedArea: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        mobilePhone: null,
        organizationId: null,
        perfectFlag: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "主体名称不能为空", trigger: "blur" }
        ],
        mobilePhone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getOrganizations();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      // 根据当前激活菜单决定查询类型
      let request = listUsers;
      if (this.activeMenu === "incomplete") {
        request = listIncompleteUsers;
      }

      request(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询单位列表 */
    getOrganizations() {
      listOrganizations().then(response => {
        this.organizations = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    //TODO
    handleAdd() {
      this.open = true;
      this.title = "添加用户";
      // 生成当前本地时间
      const now = new Date();
      const formattedTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
      this.form = {
        registerTime: formattedTime,
        memberFlag: "0",
        perfectFlag: "0",
        userStatus: "0"
      };
      this.selectedArea = [];
    },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   const id = row.id || this.ids[0];
    //   getUser(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改用户";
    //     // 设置省市区
    //     if (this.form.province && this.form.city && this.form.district) {
    //       // 注意：这里需要将字符串ID转换为数字，以便级联选择器正确显示
    //       this.selectedArea = [
    //         parseInt(this.form.province),
    //         parseInt(this.form.city),
    //         parseInt(this.form.district)
    //       ];
    //     } else {
    //       this.selectedArea = [];
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       // 确保省市区数据已正确设置
    //       if (this.selectedArea && this.selectedArea.length === 3) {
    //         this.form.province = this.selectedArea[0].toString();
    //         this.form.city = this.selectedArea[1].toString();
    //         this.form.district = this.selectedArea[2].toString();
    //       }
    //
    //       if (this.form.id != null) {
    //         updateUser(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addUser(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.resetForm("form");
    },
    /** 表单重置 */
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
      this.form = {};
      this.selectedArea = [];
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 菜单选择 */
    handleMenuSelect(index) {
      this.activeMenu = index;
      this.queryParams.organizationId = null;
      if (index.startsWith('org_')) {
        this.queryParams.organizationId = index.split('_')[1];
      }
      this.getList();
    },
    /** 格式化日期 */
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
    },
    /** 懒加载省市区数据 */
    async loadAreaData(node, resolve) {
      const { level } = node;
      let data = [];

      try {
        if (level === 0) {
          // 加载省份数据
          const response = await getAllProvinces();
          data = response.data;
        } else if (level === 1) {
          // 加载城市数据
          const provinceId = node.value;
          const response = await getCitiesByProvinceId(provinceId);
          data = response.data;
        } else if (level === 2) {
          // 加载区县数据
          const cityId = node.value;
          const response = await getDistrictsByCityId(cityId);
          data = response.data;
        }
        resolve(data);
      } catch (error) {
        console.error('加载省市区数据失败:', error);
        resolve([]);
      }
    },
    // /** 省市区选择变化处理 */
    // handleAreaChange(value) {
    //   if (value && value.length === 3) {
    //     // 设置表单中的省市区字段为ID字符串
    //     this.form.province = value[0].toString();  // 省ID
    //     this.form.city = value[1].toString();      // 市ID
    //     this.form.district = value[2].toString();  // 区ID
    //   } else {
    //     this.form.province = null;
    //     this.form.city = null;
    //     this.form.district = null;
    //   }
    // }
    /** 省市区选择变化处理 */
    handleAreaChange(value) {
      if (value && value.length === 3) {
        // 设置表单中的省市区字段为ID
        this.form.provinceId = value[0];  // 省ID
        this.form.cityId = value[1];      // 市ID
        this.form.districtId = value[2];  // 区ID
      } else {
        this.form.provinceId = null;
        this.form.cityId = null;
        this.form.districtId = null;
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保省市区数据已正确设置
          if (this.selectedArea && this.selectedArea.length === 3) {
            this.form.provinceId = this.selectedArea[0];
            this.form.cityId = this.selectedArea[1];
            this.form.districtId = this.selectedArea[2];
          }

          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              console.log(this.form)
              console.log( response);
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids[0];
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
        // 设置省市区
        if (this.form.provinceId && this.form.cityId && this.form.districtId) {
          this.selectedArea = [
            this.form.provinceId,
            this.form.cityId,
            this.form.districtId
          ];
        } else {
          this.selectedArea = [];
        }
      });
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
